#include "mainwindow.h"
#include <QApplication>
#include <QJsonDocument>
#include <QJsonValue>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonParseError>
#include <QFile>
#include <QDebug>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    //w.show();

    // 解析json文档
    QJsonParseError error;
    QFile file("../../test.json");
    QByteArray jsonByteArray;
    file.open(QFile::ReadOnly);
    jsonByteArray = file.readAll();
    file.close();
    QJsonDocument jsonDocument = QJsonDocument::fromJson(jsonByteArray, &error);
    if(error.error == QJsonParseError::NoError){
        if(jsonDocument.isEmpty()){
            qDebug() << "json is empty";
        }else if(jsonDocument.isArray()){
            // 解析json数组
            qDebug() << "jsonArray";
        }else if(jsonDocument.isObject()){
            // 解析json对象
            qDebug() << "jsonObject";
            QJsonObject jsonObject = jsonDocument.object();
            qDebug() << jsonObject.keys();
            QJsonValue company = jsonObject.value("company");
            qDebug() << "公司名字: " << company.toString();

            QJsonValue employees = jsonObject.value("employees");
            QJsonArray employeesArray = employees.toArray();

            QJsonValue employee1 = employeesArray.at(0);
            QJsonValue employee2 = employeesArray.at(1);
            QJsonValue employee3 = employeesArray.at(2);
            qDebug() << "员工信息：";
            qDebug() << employee1.toObject().value("name").toString() << employee1.toObject().value("age").toInt();
            qDebug() << employee2.toObject().value("name").toString() << employee2.toObject().value("age").toInt();
            qDebug() << employee3.toObject().value("name").toString() << employee3.toObject().value("age").toInt();
        }
    }else{
        qDebug() << error.errorString();
    }

    // 创建json文档
    QJsonObject employee0 = {{"name", "tangseng"}, {"age", 20}};
    QJsonObject employee1 = {{"name", "sunwukong"}, {"age", 500}};
    QJsonObject employee2 = {{"name", "zhubajie"}, {"age", 400}};
    QJsonObject employee3 = {{"name", "shaheshang"}, {"age", 300}};
    QJsonArray employeeArray = {employee0, employee1, employee2, employee3};
    QJsonObject xyjObject = {{"company", "xiyouji"}, {"employees", employeeArray}};
    QJsonDocument xyjDoc(xyjObject);

    QFile file1("../../xyj.json");
    file1.open(QFile::WriteOnly | QFile::Truncate);
    file1.write(xyjDoc.toJson());
    file1.close();


    return a.exec();
}
